package com.mcp.mcpserver.service;

import com.mcp.mcpserver.config.DynamicDataSource;
import com.mcp.mcpserver.exception.DataSourceException;
import com.mcp.mcpserver.model.McpResponse;
import com.mcp.mcpserver.repository.InMemoryDataSourceRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
/**
 * @author zhangxin569
 * @date 2025/8/6
 */
@Service
public class DatabaseService {
    private static final Logger log = LoggerFactory.getLogger(DatabaseService.class);
    /**
     *TODO:  NamedParameterJdbcTemplate 命名参数确保用户输入 需整体调整
     */
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private InMemoryDataSourceRepository repository;

    public McpResponse executeQuery(String dataSourceName, String query, Map<String, Object> params) {
        // 方便测试可先注释掉
//        if (!repository.existsByName(dataSourceName) || dataSourceName == null) {
//            return McpResponse.error("INVALID_DATASOURCE", "无效的数据源: " + dataSourceName);
//        }
        try {
            DynamicDataSource.setDataSourceKey(dataSourceName);

            List<Map<String, Object>> results;
            if (params == null || params.isEmpty()) {
                results = jdbcTemplate.queryForList(query);
            } else {
                results = jdbcTemplate.queryForList(query, params.values().toArray());
            }

            return McpResponse.success(results);
        } catch (DataAccessException e) {
            return McpResponse.error("DATABASE_ERROR", e.getMostSpecificCause().getMessage());
        } catch (Exception e) {
            return McpResponse.error("SYSTEM_ERROR", e.getMessage());
        } finally {
            DynamicDataSource.clearDataSourceKey();
        }
    }

    public McpResponse executeUpdate(String dataSourceName, String query, Map<String, Object> params) {
        try {
            DynamicDataSource.setDataSourceKey(dataSourceName);

            int affectedRows;
            if (params == null || params.isEmpty()) {
                affectedRows = jdbcTemplate.update(query);
            } else {
                log.info("111111111111111111111 " + params.values().toString());
                affectedRows = jdbcTemplate.update(query, params.values().toArray());
            }

            return McpResponse.success(Map.of("affected_rows", affectedRows));
        } catch (DataAccessException e) {
            return McpResponse.error("DATABASE_ERROR", e.getMostSpecificCause().getMessage());
        } catch (Exception e) {
            return McpResponse.error("SYSTEM_ERROR", e.getMessage());
        } finally {
            DynamicDataSource.clearDataSourceKey();
        }
    }
}